<?php

class CustReturnToSuppliersController extends AppController {

    var $name = 'CustReturnToSuppliers';
    var $pageTitle = 'Return Product from Inventory to Other Vendor.';
    var $viewPath = 'customers/returns/cust_return_to_suppliers';
    /**
     * @var array Class Model ที่ใช้
     */
    var $uses = array('CRtSH', 'CRtS', 'CustProductSite', 'ProductSerial', 'Customer', 'Site', 'User', 'RunningNo', 'Supplier', 'CRS');
    var $paginate = array(
        'CRtSH' => array(
            'order' => 'CRtSH.id DESC'
        )
    );
    var $components = array('Email');

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'main_cust_returns');
        $this->set('tabMenu', 'tabmenus/customer/returns');

        $this->_checkPrintView();
    }

    function display() {
        parent::display('CRtSH');
        $this->paginate['CRtSH']['contain'] = array('Supplier', 'CRS');

        $this->_checkSite('CRtSH');
        $this->_paging('CRtSH');
    }

    function save() {
        $is_success = true;
        $crh_id = null;
        if ($this->data['mode'] == 'add') {
            $is_success = $this->_save_return();
        } else { // mode == 'edit'
            $this->CRtSH->id = $this->data['CRtSH']['id'];
            $is_success = $this->CRtSH->saveField('remark', $this->data['CRtSH']['remark']);
            $is_success &= $this->CRtSH->saveField('collector_id', $this->Auth->user('id'));
        }

        if ($is_success) {
            $crh_id = $this->CRtSH->id;
            $this->Session->setFlash("Save succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Save fail !", 'flash/fail');
        }

        $this->data['CRtS'] = null;
        $this->setAction('view', $crh_id);
    }

    function _save_return() {
        $crh_id = null;
        $is_success = true;

        // เรียงลำดับรายการใหม่ กรณีลบแถว Index เปลี่ยน
        $this->adjustRowIndex($this->data['CRtS']);

        // ตรวจสอบว่ามีสินค้าอยู่ในใบ ItsStockInHead
        if (count($this->data['CRtS']) == 0) {
            $this->Session->setFlash("You didn't have any return product!", 'flash/fail');
            $is_success = false;
            unset($this->data);
        } else {
            $this->CRtSH->query("BEGIN");
            $collector_id = $this->Auth->user('id');
            $customer_id = $this->Auth->user('customer_id');
            $site_id = $this->Auth->user('site_id');

            // Generate return no
            $this->Customer->id = $customer_id;
            $cust_no = $this->Customer->field('cust_no');
            $this->Site->id = $site_id;
            $site_no = $this->Site->field('site_no');
            $year = $this->Utility->getThaiYear();
            $runno = $this->RunningNo->getNextStockNo(RunningNo::CUST_RETURN_TYPE, $year, $customer_id);
            $this->data['CRtSH']['return_no'] = $cust_no . '-' . $site_no . '-' . RunningNo::CUST_RETURN_TYPE . '-' . $year . $runno;

            $this->data['CRtSH']['customer_id'] = $customer_id;
            $this->data['CRtSH']['site_id'] = $site_id;
            $this->data['CRtSH']['collector_id'] = $collector_id;
            $this->data['CRtSH']['cust_return_status_id'] = CRS::RETURNING;

            if ($this->CRtSH->saveAll($this->data, array('validate' => 'first', 'atomic' => false)) == true) {    // ถ้าไม่ใช่จะ return array error field
                $crh_id = $this->CRtSH->id;
                foreach ($this->data['CRtS'] as $cR) {
                    // Update Cust Product Site current stock
                    $return_qty = $cR['return_qty'];
                    $this->CustProductSite->id = $cR['cust_product_site_id'];
                    $is_success &= $this->CustProductSite->removeCurrentStock($this->CustProductSite->id, $return_qty);

                    $this->CRtS->contain();
                    $_cr = $this->CRtS->find('first',
                                    array(
                                        'conditions' => array(
                                            'CRtS.product_id' => $cR['product_id'],
                                            'cust_return_to_supplier_head_id' => $crh_id,
                                        ),
                                        'fields' => array('id')
                                    )
                    );

                    $PSs = array();
                    // ถ้าเป็น IE 6 ไม่ส่ง Product Serial มา
                    $is_ie6 = (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== FALSE);
                    if ($is_ie6 || empty($cR['ProductSerial'])) {
                        $this->ProductSerial->contain();
                        $PSs = $this->ProductSerial->find('all', array(
                                    'conditions' => array(
                                        'cust_product_site_id' => $cR['cust_product_site_id'],
                                        'cust_reserve_id' => null, // ไม่ใช่ชิ้นที่ถูกจอง
                                        'cust_stock_out_id' => null,
                                        'is_active_flag' => true,
                                        'cust_stock_in_id > 0'  // stock in เข้าไปแล้วด้วย จำเป็นกับการ Cancel Dispatch
                                    ),
                                    'order' => array('stock_out_priority ASC'),
                                    'limit' => $return_qty
                                        )
                        );
                    } else {
                        $PSs = $cR['ProductSerial'];
                    }

                    // บันทึก Product Serial ว่ามีการ return
                    foreach ($PSs as $_ps) {
                        if ($is_ie6 || isset($_ps['return'])) {
                            $data = array();
                            $data['ProductSerial']['id'] = $is_ie6 ? $_ps['ProductSerial']['id'] : $_ps['id'];
                            $data['ProductSerial']['cust_stock_out_id'] = $_cr['CRtS']['id'];
                            $data['ProductSerial']['cust_stock_out_type'] = CRtS::CUST_STOCK_OUT_TYPE;

                            $this->ProductSerial->create();
                            $is_success &= $this->ProductSerial->save($data);
                        }
                    }
                }
            } else {
                $is_success = false;
            }

            if ($is_success) {
                $this->CRtSH->query("COMMIT");
                ;
                $crh_id = $this->CRtSH->id;
                $this->_sendEmail($crh_id);
            } else {
                $this->CRtSH->query("ROLLBACK");
            }
        }
        return $is_success;
    }

    function _sendEmail($crh_id) {
        $userName = $this->Auth->user('name');
        $this->Customer->id = $this->Auth->user('customer_id');
        $customerName = $this->Customer->field('name');
        $this->Site->id = $this->Auth->user('site_id');
        $siteName = $this->Site->field('name');

        // ส่ง e-mail กลับหา admin และ ผู้ดูแลแต่ละ customer (ถ้ามี)
        $email_to = $this->requestAction('system_preferences/get/contact_email');
        $response_email = $this->Customer->field('response_email');
        if (!empty($response_email)) {
            $email_to .= ", " . $response_email;
        }
        $this->Email->to = $email_to;

        $this->Email->from = "{$userName} {$customerName} {$siteName} <{$this->Auth->user('email')}>";
        $this->CRtSH->id = $crh_id;
        $this->Email->subject = 'VMI : Customer return ' . $this->CRtSH->field('return_no');
        $this->Email->template = 'customer/return/cust_return_to_supplier';
        $this->Email->sendAs = 'html';
        //$this->Email->delivery  = 'debug';

        $this->set('userName', $userName);
        $this->set('customerName', $customerName);
        $this->set('siteName', $siteName);
        $this->set('crh_id', $crh_id);
        $this->Supplier->id = $this->CRtSH->field('supplier_id');
        $this->set('vendor', $this->Supplier->field('name'));
        $this->Email->send();

//    debug( $this->Session->read( 'Message.email' ) );
    }

    function view($id = null) {
        // mode edit
        if ($id != null) {
            $this->CRtSH->contain(array('Customer', 'Site', 'Supplier', 'CRS',
                'CRtS' => array('Product' => array('supplier_part_no', 'text', 'Unit'), 'CustProductSite')));
            $this->data = $this->CRtSH->findById($id);

            $this->_neighbors($id, $this->CRtSH, array('fields' => array('id', 'return_no')));
            $this->set('mode', 'edit');
        } else {

            $this->set('return_by', $this->Auth->user('name'));
            $this->set('today', date("d/m/Y"));
            $this->set('mode', 'add');
        }
    }

    function print_view($id) {
        $this->layout = 'print';
        $this->data = $this->CRtSH->findForPrintById($id);
    }

    function json_find_by_part_no() {
        $this->RequestHandler->setContent('json');
        $this->layout = 'ajax';

        $this->CustProductSite->contain(array('Product' => array('Unit'), 'Supplier'));
        $data = $this->CustProductSite->find('first', array('conditions' => array(
                        'OR' => array(
                            'Product.supplier_part_no' => $this->data['part_no'],
                            'CustProductSite.stock_code' => $this->data['part_no'],
                        ),
                        'CustProductSite.site_id' => $this->Auth->user('site_id')
                    )
                        )
        );

        $this->set('data', $data);
        // view เก็บอยู่ใน element
        $this->viewPath = 'elements';
        $this->render('ajax/json');
    }

    /**
     * หา ProductSerial ตาม cust_stock_out_id
     */
    function json_find_product_serials_by_cust_product_site_id() {
        $this->RequestHandler->setContent('json');

        $this->ProductSerial->contain('CustLocation');
        $data = $this->ProductSerial->find('all',
                        array(
                            'conditions' => array(
                                'cust_product_site_id' => $this->data['cust_product_site_id'],
                                'cust_stock_in_id <>' => null, // อยู่ในคลังแล้ว
                                'cust_stock_out_id' => null,
                                'is_active_flag' => true, // ไม่ได้ return
                            ),
                            'order' => 'stock_out_priority ASC'
                        )
        );

        $this->set('data', $data);
        // view เก็บอยู่ใน element
        $this->viewPath = 'elements';
        $this->render('ajax/json');
    }

}

?>